<!-- 创建宗亲荟表单 -->
<template>
  <!-- 创建宗亲荟表单 -->
  <view class="create-form-section">
    <view class="form-header">
      <text class="form-title">创建宗亲荟</text>
      <view class="back-btn" @click="handleBack">
        <text class="back-text">返回</text>
      </view>
    </view>
    <view ref="formRef" class="clan-sion-form">
      <!-- 宗亲荟名称 -->
      <view class="form-item">
        <text class="item-label required">宗亲荟名称</text>
        <input
          v-model="formData.name"
          class="item-input"
          placeholder="请输入宗亲荟名称"
          maxlength="50"
        />
      </view>

      <!-- 位置 -->
      <view class="form-item">
        <text class="item-label required">位置</text>
        <input
          v-model="formData.location"
          class="item-input"
          placeholder="请输入宗亲荟位置"
          maxlength="100"
        />
        <view class="map-container">
          <Amap
            :center="mapCenter"
            :zoom="mapZoom"
            :markers="mapMarkers"
            :show-search="true"
            @location-selected="handleMapLocationSelected"
          />
          <wd-button size="small" block @click="handleSelectLocation">选择位置</wd-button>
          <!-- <wd-button size="small" block @click="handleTestMapUpdate" style="margin-top: 8rpx;">测试地图更新</wd-button> -->
        </view>
      </view>
      <!-- 简介 -->
      <view class="form-item">
        <text class="item-label required">简介</text>
        <textarea
          v-model="formData.history"
          class="item-textarea"
          placeholder="请输入宗亲荟简介"
          :maxlength="500"
          show-count
        />
      </view>

      <!-- 收款码 -->
      <view class="form-item">
        <text class="item-label required">收款码</text>
        <view class="upload-section">
          <view class="upload-area" @click="handleUploadQRCode">
            <view v-if="!formData.qrcodeUrl" class="upload-placeholder">
              <view class="upload-icon">+</view>
              <text class="upload-text">请上传微信或支付宝收款码</text>
              <text class="upload-hint">大小不超过2MB</text>
            </view>
            <view v-else class="upload-preview">
              <image :src="formData.qrcodeUrl" mode="aspectFit" class="preview-image" />
              <view class="preview-overlay">
                <view class="preview-actions">
                  <view class="action-btn" @click.stop="handlePreviewQRCode">
                    <text class="action-text">预览</text>
                  </view>
                  <view class="action-btn delete" @click.stop="handleDeleteQRCode">
                    <text class="action-text">删除</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="form-actions">
      <view class="action-btn secondary" @click="handleBack">
        <text class="btn-text">取消</text>
      </view>
      <view class="action-btn primary" @click="handleSubmitForm">
        <text class="btn-text">提交</text>
      </view>
    </view>
  </view>

  <!-- 地图选择组件 -->
  <mapSelect
    v-model:visible="showMapSelect"
    :initial-location="currentLocation"
    @confirm="handleLocationConfirm"
  />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, defineComponent } from "vue";
import FileAPI, { type FileInfo } from "@/api/file";
import ClanAssociationAPI from "@/api/genealogy/clanAssociation";
import Amap from "@/components/map/Amap.vue";
import mapSelect from "./mapSelect.vue";

// 表单数据接口
interface ClanFormData {
  name: string;
  location: string;
  history: string;
  qrcodeUrl: string;
  longitude?: number;
  latitude?: number;
}

// 位置信息接口
interface LocationInfo {
  name: string;
  address: string;
  longitude: number;
  latitude: number;
}
// 定义子组件传递事件
const emit = defineEmits(["closeCreateForm"]);
// 创建宗亲荟荟表单判断
const showCreateFormFlag = ref(false);
const formRef = ref();
// 获取表单数据
// 表单数据
const formData = reactive<ClanFormData>({
  name: "",
  location: "江西省南昌市青山湖区康华大厦",
  history: "",
  qrcodeUrl: "",
  longitude: 115.858197,
  latitude: 28.682892,
});

// 地图选择相关
const showMapSelect = ref(false);
const currentLocation = computed<LocationInfo | undefined>(() => {
  if (formData.longitude && formData.latitude) {
    return {
      name: formData.name || "宗亲荟位置",
      address: formData.location,
      longitude: formData.longitude,
      latitude: formData.latitude,
    };
  }
  return undefined;
});

// 地图相关数据
const mapCenter = computed(() => {
  const center = [formData.longitude || 115.858197, formData.latitude || 28.682892];
  console.log("地图中心点计算:", center);
  return center;
});

const mapZoom = ref(15);
const mapMarkers = computed(() => {
  const markers = [
    {
      position: [formData.longitude || 115.858197, formData.latitude || 28.682892],
      title: formData.name || "宗亲荟位置",
      icon: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/2a6a85534eea442cb1a7864c503e9d67.png",
    },
  ];
  console.log("地图标记计算:", markers);
  return markers;
});

// 监听表单数据变化，确保地图更新
watch(
  () => [formData.longitude, formData.latitude, formData.name],
  () => {
    console.log("表单数据变化，地图需要更新");
  },
  { deep: true }
);

// 选择位置
const handleSelectLocation = () => {
  showMapSelect.value = true;
};
// 提交表单
const handleSubmitForm = async () => {
  // 表单验证
  const { isValid, errors } = validateForm();

  if (!isValid) {
    uni.showToast({
      title: errors[0] || "请填写必填项",
      icon: "none",
    });
    return;
  }

  // 显示加载提示
  uni.showLoading({
    title: "提交中...",
  });
  try {
    // 调用API提交表单数据
    await ClanAssociationAPI.createClan({
      name: formData.name,
      location: formData.location,
      history: formData.history,
      qrcodeUrl: formData.qrcodeUrl,
      longitude: formData.longitude,
      latitude: formData.latitude,
    })
      .then((res) => {
        uni.showToast({
          title: "创建成功",
          icon: "success",
        });
        uni.hideLoading();
        // 关闭表单
        emit("closeCreateForm");
      })
      .catch((err) => {
        uni.showToast({
          title: "创建失败",
          icon: "error",
        });
        uni.hideLoading();
      });
  } catch (error) {
    uni.showToast({
      title: "创建失败",
      icon: "error",
    });
  }
};

// 返回按钮
const handleBack = () => {
  uni.navigateBack();
};
// 位置确认回调
const handleLocationConfirm = (location: LocationInfo) => {
  console.log("接收到位置确认:", location);

  // 更新表单数据
  formData.location = location.address;
  formData.longitude = location.longitude;
  formData.latitude = location.latitude;
};

// 地图搜索位置选择回调
const handleMapLocationSelected = (location: {
  name: string;
  address: string;
  longitude: number;
  latitude: number;
}) => {
  console.log("地图搜索选择位置:", location);

  // 更新表单数据
  formData.location = location.address || location.name;
  formData.longitude = location.longitude;
  formData.latitude = location.latitude;
};

// 上传收款码
const handleUploadQRCode = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];

      // 检查文件大小（2MB = 2 * 1024 * 1024 bytes）
      uni.getFileInfo({
        filePath: tempFilePath,
        success: (fileInfo) => {
          const maxSize = 2 * 1024 * 1024; // 2MB
          if (fileInfo.size > maxSize) {
            uni.showToast({
              title: "文件大小不能超过2MB",
              icon: "error",
            });
            return;
          }

          // 上传文件到服务器
          uploadFile(tempFilePath);
        },
        fail: () => {
          uni.showToast({
            title: "获取文件信息失败",
            icon: "error",
          });
        },
      });
    },
    fail: () => {
      uni.showToast({
        title: "选择图片失败",
        icon: "error",
      });
    },
  });
};

// 上传文件到服务器
const uploadFile = (filePath: string) => {
  uni.showLoading({
    title: "上传中...",
  });

  FileAPI.upload(filePath)
    .then((fileInfo: FileInfo) => {
      uni.hideLoading();
      formData.qrcodeUrl = fileInfo.url;
      uni.showToast({
        title: "上传成功",
        icon: "success",
      });
    })
    .catch((error) => {
      uni.hideLoading();
      console.error("上传失败:", error);
      uni.showToast({
        title: error.message || "上传失败",
        icon: "error",
      });
    });
};

// 预览收款码
const handlePreviewQRCode = () => {
  if (formData.qrcodeUrl) {
    uni.previewImage({
      urls: [formData.qrcodeUrl],
      current: formData.qrcodeUrl,
    });
  }
};

// 删除收款码
const handleDeleteQRCode = () => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除收款码吗？",
    success: (res) => {
      if (res.confirm) {
        formData.qrcodeUrl = "";
        uni.showToast({
          title: "删除成功",
          icon: "success",
        });
      }
    },
  });
};

// 测试地图更新
const handleTestMapUpdate = () => {
  console.log("测试地图更新");
  // 模拟表单数据变化，触发watch
  formData.longitude = 115.858197 + 0.001; // 轻微改变经度
  formData.latitude = 28.682892 + 0.001; // 轻微改变纬度
  formData.name = "测试位置"; // 改变名称
  console.log("更新后的表单数据:", formData);
  console.log("更新后的地图中心点:", mapCenter.value);
  console.log("更新后的地图标记:", mapMarkers.value);
};

// 表单验证规则
const validateForm = () => {
  const errors: string[] = [];

  if (!formData.name.trim()) {
    errors.push("请输入宗亲荟名称");
  }

  if (!formData.location.trim()) {
    errors.push("请输入宗亲荟位置");
  }
  if (!formData.history.trim()) {
    errors.push("请输入简介");
  }
  if (!formData.qrcodeUrl.trim()) {
    errors.push("请上传收款码");
  }

  return {
    isValid: errors.length === 0,
    errors,
  };
};

// 获取表单数据
const getFormData = () => {
  return formData;
};

// 重置表单
const resetForm = () => {
  formData.name = "";
  formData.location = "江西省南昌市青山湖区康华大厦";
  formData.history = "";
  formData.qrcodeUrl = "";
  formData.longitude = 115.858197;
  formData.latitude = 28.682892;
};

// 设置表单数据
const setFormData = (data: Partial<ClanFormData>) => {
  Object.assign(formData, data);
};

// 暴露方法给父组件
defineExpose({
  getFormData,
  resetForm,
  setFormData,
  validateForm,
});
</script>

<style lang="scss" scoped>
/* 创建表单样式 */
.create-form-section {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.back-btn {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  background-color: #f0f0f0;
  transition: all 0.3s ease;
}

.back-btn:active {
  background-color: #e0e0e0;
}

.back-text {
  font-size: 26rpx;
  color: #666;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.form-actions .action-btn {
  flex: 1;
  margin: 0;
}
.action-btn {
  padding: 24rpx 40rpx;
  border-radius: 50rpx;
  text-align: center;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.action-btn.primary {
  background: #4d80f0;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10rpx);
}

.action-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
}
// 创建表单样式 结束
.clan-sion-form {
  padding: 30rpx;
  background-color: #fff;
}

.form-item {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  font-weight: 500;

  &.required {
    color: #333;

    &::before {
      content: "*";
      color: #ff4d4f;
      margin-right: 4rpx;
    }
  }
}

.item-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
  transition: all 0.3s ease;

  &:focus {
    border-color: #1989fa;
    box-shadow: 0 0 0 2rpx rgba(25, 137, 250, 0.1);
  }

  &::placeholder {
    color: #999;
  }

  &:disabled {
    background-color: #f5f5f5;
    color: #666;
  }
}

.item-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 24rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
  transition: all 0.3s ease;
  line-height: 1.6;
  resize: none;

  &:focus {
    border-color: #1989fa;
    box-shadow: 0 0 0 2rpx rgba(25, 137, 250, 0.1);
  }

  &::placeholder {
    color: #999;
  }
}

.map-container {
  margin-top: 16rpx;

  .wd-button {
    margin-top: 16rpx;
  }
}

/* 上传区域样式 */
.upload-section {
  width: 100%;
}

.upload-area {
  width: 100%;
  height: 300rpx;
  border: 2rpx dashed #d9d9d9;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #1989fa;
    background-color: #f0f8ff;
  }

  &:active {
    transform: scale(0.98);
  }
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.upload-icon {
  font-size: 60rpx;
  color: #d9d9d9;
  margin-bottom: 16rpx;
  font-weight: 300;
}

.upload-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.upload-hint {
  font-size: 24rpx;
  color: #999;
}

.upload-preview {
  width: 100%;
  height: 100%;
  position: relative;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .preview-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;

    &:hover {
      opacity: 1;
    }
  }

  .preview-actions {
    display: flex;
    gap: 20rpx;
  }

  .action-btn {
    padding: 12rpx 24rpx;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 20rpx;
    transition: all 0.3s ease;

    &:hover {
      background-color: #fff;
    }

    &.delete {
      background-color: rgba(255, 77, 79, 0.9);

      &:hover {
        background-color: #ff4d4f;
      }

      .action-text {
        color: #fff;
      }
    }
  }

  .action-text {
    font-size: 24rpx;
    color: #333;
    font-weight: 500;
  }
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .clan-sion-form {
    padding: 20rpx;
  }

  .item-input {
    height: 70rpx;
    font-size: 26rpx;
  }

  .item-textarea {
    min-height: 180rpx;
    font-size: 26rpx;
  }

  .item-label {
    font-size: 26rpx;
  }

  .upload-area {
    height: 250rpx;
  }

  .upload-icon {
    font-size: 50rpx;
  }

  .upload-text {
    font-size: 26rpx;
  }

  .upload-hint {
    font-size: 22rpx;
  }
}
</style>
